from model.entity import HealthCard, GlucoseData
from dbCon import get_db_connection

class HealthService:
    def create_health_card(self, health_card):
        """创建健康卡：写入数据库"""
        conn = get_db_connection()
        cursor = conn.cursor()
        sql = """INSERT INTO health_cards (user_id, bmi, blood_pressure, blood_lipids, 
                 skin_thickness, insulin_level, diabetes_genetic_function, pregnancies) 
                 VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"""
        values = (health_card.user_id, health_card.bmi, health_card.blood_pressure,
                  health_card.blood_lipids, health_card.skin_thickness,
                  health_card.insulin_level, health_card.diabetes_genetic_function,
                  health_card.pregnancies)  # 新增：怀孕次数
        try:
            cursor.execute(sql, values)
            conn.commit()
            return True
        except Exception as e:
            print(f"创建健康卡失败: {e}")
            conn.rollback()
            return False
        finally:
            cursor.close()
            conn.close()

    def get_health_card_by_user(self, user_id):
        """根据用户 ID 查询健康卡"""
        conn = get_db_connection()
        cursor = conn.cursor()
        sql = "SELECT * FROM health_cards WHERE user_id = %s"
        cursor.execute(sql, (user_id,))
        row = cursor.fetchone()
        if row:
            return HealthCard(
                id=row[0],
                user_id=row[1],
                bmi=row[2],
                blood_pressure=row[3],
                blood_lipids=row[4],
                skin_thickness=row[5],
                insulin_level=row[6],
                diabetes_genetic_function=row[7],
                pregnancies=row[8],  # 新增：怀孕次数（注意索引可能需要调整）
                created_at=row[9]    # 索引+1：created_at 位置后移
            )
        return None

    def add_glucose_data(self, glucose_data):
        """上传血糖数据：写入数据库"""
        conn = get_db_connection()
        cursor = conn.cursor()
        sql = """INSERT INTO glucose_data (user_id, glucose_level, recorded_at) 
                 VALUES (%s, %s, %s)"""
        values = (glucose_data.user_id, glucose_data.glucose_level, glucose_data.recorded_at)
        try:
            cursor.execute(sql, values)
            conn.commit()
            return True
        except Exception as e:
            print(f"上传血糖数据失败: {e}")
            conn.rollback()
            return False
        finally:
            cursor.close()
            conn.close()